package com.jf.blog_jf04.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jf.blog_jf04.bean.Blog;
import com.jf.blog_jf04.bean.BlogTag;
import com.jf.blog_jf04.bean.Comment;
import com.jf.blog_jf04.bean.Userinfo;
import com.jf.blog_jf04.data.PageInfo;
import com.jf.blog_jf04.data.dto.BlogDto;
import com.jf.blog_jf04.data.ov.BlogSearchOV;
import com.jf.blog_jf04.data.ov.BlogUpdateOV;
import com.jf.blog_jf04.mapper.BlogMapper;
import com.jf.blog_jf04.service.BlogService;
import com.jf.blog_jf04.service.BlogTagService;
import com.jf.blog_jf04.service.CommentService;
import com.jf.blog_jf04.utils.BeanConvertUtils;
import com.jf.blog_jf04.utils.LoginUtils;
import com.jf.blog_jf04.utils.MyConstants;
import com.jf.blog_jf04.utils.R;
import com.jf.blog_jf04.utils.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author pang6
 * @description 针对表【blog(博客表)】的数据库操作Service实现
 * @createDate 2025-10-18 14:32:11
 */
@Service
@Transactional
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog>
        implements BlogService {

    @Autowired
    private BlogTagService blogTagService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private BlogMapper blogMapper;

    @Override
    public void saveOrUpdate(BlogUpdateOV form) {
        Blog blog = BeanConvertUtils.copyBean(form, Blog.class);
        if (blog.getBlogStatus() == 1) {
            blog.setApplyTime(new Date());
        }

        if (blog.getBlogId() != null) {
            Blog search = this.getById(blog.getBlogId());
            if (!search.getCreateUser().equals(LoginUtils.getLoginUserinfo().getUserinfoId())) {
                throw new BusinessException("禁止修改他人博客！");
            }
        }

        /*调用mybatis-plus自带的saveOrUpdate*/
        this.saveOrUpdate(blog);
        /*删除关联标签*/
        blogTagService.remove(new QueryWrapper<BlogTag>().eq("blog_id", blog.getBlogId()));
        /*批量添加标签*/
        List<BlogTag> blogTagList = form.getTagIds().stream().map(item -> {
            BlogTag blogTag = new BlogTag();
            blogTag.setBlogId(blog.getBlogId());
            blogTag.setTagId(item);
            return blogTag;
        }).collect(Collectors.toList());
        blogTagService.saveBatch(blogTagList);
    }

    @Override
    public R getPage(PageInfo pageInfo, BlogSearchOV form) {
        Userinfo login = LoginUtils.getLoginUserinfo();
        if (login.getRoleId() == MyConstants.ROLE_VIP) {
            form.setCreateUser(login.getUserinfoId());
        } else {
            if (form.getType() == null || form.getType() == 2) {
                form.setCreateUser(login.getUserinfoId());
            }
        }

        QueryWrapper<Blog> queryWrapper = new QueryWrapper<>();
        if (form.getApplyTimeRange() != null && form.getApplyTimeRange().length > 0) {
            queryWrapper.between("apply_time", form.getApplyTimeRange()[0], form.getApplyTimeRange()[1]);
        }

        IPage<Blog> iPage = this.page(pageInfo.setPage(), queryWrapper
                .like(StringUtils.hasText(form.getTitle()), "title", form.getTitle())
                .eq(form.getCategoryId() != null, "category_id", form.getCategoryId())
                .eq(form.getHasComment() != null, "has_comment", form.getHasComment())
                .eq(form.getStatus() != null, "status", form.getStatus())
                .eq(form.getBlogStatus() != null, "blog_status", form.getBlogStatus())
                .eq(form.getCreateUser() != null, "create_user", form.getCreateUser())
        );
        List<BlogDto> list = BeanConvertUtils.coptList(iPage.getRecords(), BlogDto.class);
        return R.success(pageInfo.setPageInfo(iPage.getTotal(), list));
    }

    @Override
    public void delete(List<Integer> ids) {
        this.removeBatchByIds(ids);
        blogTagService.remove(new QueryWrapper<BlogTag>().in("blog_id", ids));
        commentService.remove(new QueryWrapper<Comment>().in("blog_id", ids));
    }

    @Override
    public void updateStatus(int blogId) {
        Blog search = this.getById(blogId);
        Blog blog = new Blog();
        blog.setStatus(search.getStatus() == 1 ? 2 : 1);
        blog.setBlogId(blogId);
        this.updateById(blog);
    }

    @Override
    public R getVipPage(long page, Integer categoryId) {
        PageInfo pageInfo = new PageInfo(page, MyConstants.VIP_PAGE_LIMIT);
        IPage<Blog> iPage = this.page(pageInfo.setPage(), new QueryWrapper<Blog>()
                .eq("create_user", LoginUtils.getVipId())
                .eq("blog_status", 1)
                .eq("status", 1)
                .eq(categoryId != null, "category_id", categoryId)
                .orderByDesc(categoryId == null, "read_count")
        );
        List<BlogDto> list = BeanConvertUtils.coptList(iPage.getRecords(), BlogDto.class);
        return R.success(pageInfo.setPageInfo(iPage.getTotal(), list));
    }

    @Override
    public R getVipBlog(int blogId) {
        Blog blog = this.getById(blogId);
        checkVipBlog(blog);
        return R.success(BeanConvertUtils.copyBean(blog, BlogDto.class));
    }

    @Override
    public R getVipPageByTagId(int page, Integer tagId) {
        if (tagId == null) {
            return getVipPage(page, null);
        }
        PageInfo pageInfo = new PageInfo(page, MyConstants.VIP_PAGE_LIMIT);
        IPage<Blog> iPage = blogMapper.getTagBlog(pageInfo.setPage(), tagId);
        List<BlogDto> list = BeanConvertUtils.coptList(iPage.getRecords(), BlogDto.class);
        return R.success(pageInfo.setPageInfo(iPage.getTotal(), list));
    }

    @Override
    public R getVipBlogDetail(int blogId) {
        Blog blog = this.getOne(new QueryWrapper<Blog>().eq("blog_id", blogId).eq("create_user", LoginUtils.getLoginUserinfo().getUserinfoId()));
        if (blog == null) {
            throw new BusinessException("编号异常！");
        }
        return R.success(BeanConvertUtils.copyBean(blog, BlogDto.class));
    }

    private void checkVipBlog(Blog blog) {
        if (blog == null || blog.getBlogStatus() == 2 || blog.getStatus() == 2) {
            throw new BusinessException("博客异常");
        }
    }
}




